package service

import (
	"MyBlogv2/blog-common/HttpCode"
	"MyBlogv2/blog-common/define"
	"MyBlogv2/blog-common/models"
	"MyBlogv2/blog-common/response"
	"github.com/gin-gonic/gin"
	"time"
)

func ApplyLink(c *gin.Context) {
	userId, _ := c.Get("userId")
	var link models.Link
	if err := c.ShouldBindJSON(&link); err != nil {
		response.ResponseError(c, HttpCode.PARAM_ERROR)
		return
	}
	link.UserId = userId.(int)
	if err := models.Db.Model(new(models.Link)).Create(&link).Error; err != nil {
		response.ResponseError(c, HttpCode.FAILURE)
		return
	}
	//TODO 发送邮件
	response.ResponseOK(c, nil)

}
func GetLinkList(c *gin.Context) {
	var linkVo []models.LinkVo
	models.Db.Model(new(models.LinkVo)).
		Table("t_link l").
		Select("l.*,u.avatar as avatar").
		Joins("left join sys_user u on l.user_id = u.id").
		Where("is_check = ?", define.IS_CHECK_YES).
		Find(&linkVo)
	response.ResponseOK(c, linkVo)

}

func GetBackLinkList(c *gin.Context) {
	var linkListVoList []models.LinkListVo
	models.Db.Model(new(models.LinkListVo)).
		Table("t_link l").
		Select("l.*,u.username as username").
		Joins("left join sys_user u on l.user_id = u.id").
		Find(&linkListVoList)
	response.ResponseOK(c, linkListVoList)
}

func SearchLink(c *gin.Context) {
	var searchLinkDto models.SearchLinkDto
	var linkListVoList []models.LinkListVo
	if err := c.ShouldBindJSON(&searchLinkDto); err != nil {
		response.ResponseError(c, HttpCode.PARAM_ERROR)
		return
	}
	db := models.Db.Model(new(models.LinkListVo)).
		Table("t_link l").
		Select("l.*,u.username as username").
		Joins("left join sys_user u on l.user_id = u.id")
	if searchLinkDto.Name != "" {
		db.Where("l.name like ?", "%"+searchLinkDto.Name+"%")
	}
	if searchLinkDto.UserName != "" {
		db.Where("u.username like ?", "%"+searchLinkDto.UserName+"%")
	}
	if searchLinkDto.IsCheck.Valid {
		db.Where("l.is_check = ?", searchLinkDto.IsCheck.Int64)
	}
	if !time.Time(searchLinkDto.StartTime).IsZero() {
		db.Where("l.created_at >= ?", searchLinkDto.StartTime)
	}
	if !time.Time(searchLinkDto.EndTime).IsZero() {
		db.Where("l.created_at <= ?", searchLinkDto.EndTime)
	}
	db.Find(&linkListVoList)
	response.ResponseOK(c, linkListVoList)
	return
}

func UpdateLinkIsCheck(c *gin.Context) {
	var linkIsCheckDto models.LinkIsCheckDto
	if err := c.ShouldBindJSON(&linkIsCheckDto); err != nil {
		response.ResponseError(c, HttpCode.PARAM_ERROR)
		return
	}
	if err := models.Db.Model(new(models.Link)).Where("id = ?", linkIsCheckDto.Id).Update("is_check", linkIsCheckDto.IsCheck).Error; err != nil {
		response.ResponseError(c, HttpCode.FAILURE)
		return
	}
	response.ResponseOK(c, nil)
	return

}

func DeleteLink(c *gin.Context) {
	var ids []int
	if err := c.ShouldBindJSON(&ids); err != nil {
		response.ResponseError(c, HttpCode.PARAM_ERROR)
		return
	}
	models.Db.Model(new(models.Link)).Where("id in (?)", ids).Delete(new(models.Link))
	response.ResponseOK(c, nil)
	return
}
